package com.stone.databinding.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.Observable;
import androidx.databinding.ObservableInt;
import androidx.lifecycle.ViewModelProviders;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

import com.stone.databinding.BR;
import com.stone.databinding.R;
import com.stone.databinding.data.IntervalTimerViewModel;
import com.stone.databinding.data.IntervalTimerViewModelFactory;
import com.stone.databinding.databinding.ActivityTwoWayBinding;

import java.util.ArrayList;

public class TwoWayActivity extends AppCompatActivity {
    private static final String SHARED_PREFS_KEY = "timer";
    private IntervalTimerViewModel intervalTimerViewModel = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityTwoWayBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_two_way);
        intervalTimerViewModel = ViewModelProviders.of(this, new IntervalTimerViewModelFactory()).get(IntervalTimerViewModel.class);
        binding.setViewmodel(intervalTimerViewModel);
        /* Save the user settings whenever they change */
        observeAndSaveTimePerSet(
                intervalTimerViewModel.getTimePerWorkSet(), R.string.prefs_timePerWorkSet);
        observeAndSaveTimePerSet(
                intervalTimerViewModel.getTimePerRestSet(), R.string.prefs_timePerRestSet);

        /* Number of sets needs a different  */
        observeAndSaveNumberOfSets(intervalTimerViewModel);

        if (savedInstanceState == null) {
            /* If this is the first run, restore shared settings */
            restorePreferences(intervalTimerViewModel);
            observeAndSaveNumberOfSets(intervalTimerViewModel);
        }
    }

    private void observeAndSaveTimePerSet(ObservableInt timePerWorkSet, int prefsKey) {
        timePerWorkSet.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @SuppressLint("CommitPrefEdits")
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                Log.d("saveTimePerWorkSet", "Saving time-per-set preference");
                SharedPreferences sharedPref = getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE);
                if (sharedPref != null) {
                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putInt(getString(prefsKey), ((ObservableInt) sender).get());
                    editor.apply();
                }
            }
        });
    }

    private void restorePreferences(IntervalTimerViewModel viewModel) {
        SharedPreferences sharedPref =
                getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE);
        if (sharedPref == null) {
            return;
        }
        String timePerWorkSetKey = getString(R.string.prefs_timePerWorkSet);
        boolean wasAnythingRestored = false;
        if (sharedPref.contains(timePerWorkSetKey)) {
            viewModel.getTimePerWorkSet().set(sharedPref.getInt(timePerWorkSetKey, 100));
            wasAnythingRestored = true;
        }
        String timePerRestSetKey = getString(R.string.prefs_timePerRestSet);
        if (sharedPref.contains(timePerRestSetKey)) {
            viewModel.getTimePerRestSet().set(sharedPref.getInt(timePerRestSetKey, 50));
            wasAnythingRestored = true;
        }
        String numberOfSetsKey = getString(R.string.prefs_numberOfSets);
        if (sharedPref.contains(numberOfSetsKey)) {
            ArrayList<Integer> numOfSets = new ArrayList<>();
            numOfSets.add(0);
            numOfSets.add(sharedPref.getInt(numberOfSetsKey, 5));
            wasAnythingRestored = true;
        }
        if (wasAnythingRestored) Log.d("saveTimePerWorkSet", "Preferences restored");
        viewModel.stopButtonClicked();
    }

    private void observeAndSaveNumberOfSets(IntervalTimerViewModel viewModel) {
        viewModel.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (propertyId == BR.numberOfSets) {
                    Log.d("saveTimePerWorkSet", "Saving number of sets preference");
                    SharedPreferences sharedPref =
                            getSharedPreferences(SHARED_PREFS_KEY, Context.MODE_PRIVATE);
                    if (sharedPref != null) {
                        SharedPreferences.Editor editor = sharedPref.edit();
                        editor.putInt(getString(R.string.prefs_numberOfSets), viewModel.getNumberOfSets().get(1));
                        editor.apply();
                    }
                }
            }
        });
    }
}
